package com.hcinfos.gsoo.ui;

import java.util.List;

import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.type.TypeReference;
import org.json.JSONObject;

import com.hcinfos.gsoo.R;
import com.hcinfos.gsoo.config.Urls;
import com.hcinfos.gsoo.enity.ChouGift;
import com.hcinfos.gsoo.enity.User;
import com.hcinfos.gsoo.util.BitmapHelp;
import com.hcinfos.gsoo.util.DialogUtil;
import com.hcinfos.gsoo.util.LogUtil;
import com.hcinfos.gsoo.util.LoginUtil;
import com.hcinfos.gsoo.util.SharePreferenceUtil;
import com.hcinfos.gsoo.util.UtilHttp;
import com.hcinfos.gsoo.view.LuckyPanView;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;

import android.app.Activity;
import android.app.Dialog;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.Toast;

/**
 * 抽奖activity
 * 
 * @author xi
 * 
 */
public class ChoujiangActivity extends Activity implements OnClickListener {
	private LuckyPanView mLuckyPanView;
	private ImageView mStartBtn;

	private ImageView back_iv;

	public final int STOP_WHEEL = 0x2210;

	public final int OBTAIN_SUCCESS = STOP_WHEEL + 1;
	public final int OBTAIN_FAIL = STOP_WHEEL + 2;
	public final int CHOU_SUCCESS = STOP_WHEEL + 3;
	public final int CHOU_FAIL = STOP_WHEEL + 4;
	public final int LOGIN_FAIL = STOP_WHEEL + 5;
	public final int LOGIN_SUCCESS = STOP_WHEEL + 6;
	public final int NEED_LOGIN = STOP_WHEEL + 7;

	private ObjectMapper mapper;

	private Dialog dialog;
	private Dialog tipDialog;
	private SharePreferenceUtil spfUtil;

	private User user;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_choujiang);
		spfUtil = new SharePreferenceUtil(this, "setting");

		user = (User) spfUtil.loadObject("user");
		dialog = DialogUtil.createProgressDialog(this, "提示", "数据初始化中...");
		tipDialog = DialogUtil.createProgressDialog(this, "提示", "积分查询中..");
		mapper = new ObjectMapper();
		back_iv = (ImageView) findViewById(R.id.back_iv);
		back_iv.setOnClickListener(this);
		mLuckyPanView = (LuckyPanView) findViewById(R.id.id_luckypan);
		mStartBtn = (ImageView) findViewById(R.id.id_start_btn);
		mStartBtn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				User user = (User) spfUtil.loadObject("user");
				if (user == null) {
					Toast.makeText(ChoujiangActivity.this, "请先登录!", 500).show();
					return;
				}

				if (!mLuckyPanView.isStart()) {
					mStartBtn.setImageResource(R.drawable.stop);
					mLuckyPanView.luckyStart(6);
					handler.sendEmptyMessageDelayed(STOP_WHEEL, 4000);

				}
			}
		});
		obtainList();
	}

	private List<ChouGift> list;

	private void obtainList() {
		dialog.show();
		HttpUtils httpUtils = UtilHttp.getHttpUtils(this);
		RequestParams params = new RequestParams();
		params.addBodyParameter("page", 1 + "");
		params.addBodyParameter("rows", 6 + "");

		httpUtils.send(HttpRequest.HttpMethod.POST,
				Urls.callnew_lotoryGiftList, params,
				new RequestCallBack<String>() {

					@Override
					public void onFailure(HttpException arg0, String arg1) {
						handler.sendEmptyMessage(OBTAIN_FAIL);
					}

					@Override
					public void onSuccess(ResponseInfo<String> arg0) {
						try {
							String result = arg0.result;
							LogUtil.d("wxf", result);
							JSONObject obj = new JSONObject(result);
							int state = obj.getInt("state");
							if (state == 200) {
								String data = obj.getString("data");
								list = mapper.readValue(data,
										new TypeReference<List<ChouGift>>() {
										});
								handler.sendEmptyMessage(OBTAIN_SUCCESS);
							} else {
								handler.sendEmptyMessage(OBTAIN_FAIL);
							}
						} catch (Exception e) {
							handler.sendEmptyMessage(OBTAIN_FAIL);
						}
					}

				});
	}

	/**
	 * 抽奖处理
	 */
	private void doChou() {

		if (user == null) {
			Toast.makeText(ChoujiangActivity.this, "请先登录!", 500).show();
			return;
		}
		HttpUtils httpUtils = UtilHttp.getHttpUtils(this);
		RequestParams params = new RequestParams();
		params.addBodyParameter("user.id", user.getId());
		httpUtils.send(HttpRequest.HttpMethod.POST, Urls.callnew_joinLotory,
				params, new RequestCallBack<String>() {

					@Override
					public void onFailure(HttpException arg0, String arg1) {
						handler.sendEmptyMessage(CHOU_FAIL);
					}

					@Override
					public void onSuccess(ResponseInfo<String> arg0) {
						try {
							String result = arg0.result;
							LogUtil.e("wxf", " doChou = " + result);
							JSONObject obj = new JSONObject(result);
							String message = obj.getString("message");
							int state = obj.getInt("state");
							if (state == 200) {
								handler.sendEmptyMessage(CHOU_SUCCESS);
							} else if (state == 500) {
								handler.sendEmptyMessage(NEED_LOGIN);
							} else {
								Message msg = handler.obtainMessage();
								msg.what = CHOU_FAIL;
								msg.obj = message;
								handler.sendMessage(msg);
							}

						} catch (Exception e) {
							handler.sendEmptyMessage(CHOU_FAIL);
						}
					}

				});
	}

	Handler handler = new Handler() {

		public void handleMessage(android.os.Message msg) {
			dialog.dismiss();
			switch (msg.what) {
			case STOP_WHEEL:
				mStartBtn.setImageResource(R.drawable.start);
				mLuckyPanView.luckyEnd();
				doChou();
				break;
			case OBTAIN_SUCCESS:
				if (list != null && list.size() > 0) {

					for (ChouGift g : list) {
						LogUtil.d("wxf", g.getGiftName());
					}
					mLuckyPanView.setList(list);
				}
				break;
			case OBTAIN_FAIL:
				Toast.makeText(ChoujiangActivity.this, "初始化失败!", 500).show();
				finish();
				break;
			case CHOU_SUCCESS:
				doLogin();
				break;
			case NEED_LOGIN:
				LoginUtil.isLoginSuccess(ChoujiangActivity.this, handler);
				break;
			case CHOU_FAIL:
				String error = "兑换失败!";
				if (msg.obj != null) {
					error = msg.obj.toString();
				}
				Toast.makeText(ChoujiangActivity.this, error, 500).show();
				tipDialog.dismiss();
				break;
			case LOGIN_FAIL:
				tipDialog.dismiss();
				break;
			case LOGIN_SUCCESS:
				tipDialog.dismiss();
				break;
			case LoginUtil.LOGIN_SUCCESS:
				doChou();
				break;
			case LoginUtil.LOGIN_FAIL:
				Toast.makeText(ChoujiangActivity.this, "抽奖失败!", 500).show();
				break;
			}
		};
	};

	@Override
	public void onClick(View v) {

		switch (v.getId()) {
		case R.id.back_iv:
			finish();
			break;
		}
	}

	private void doLogin() {
		User user = (User) spfUtil.loadObject("user");
		if (user == null)
			return;
		HttpUtils http = UtilHttp.getHttpUtils(this);
		RequestParams params = new RequestParams();
		params.addBodyParameter("user.email", user.getEmail());
		params.addBodyParameter("user.password", user.getPassword());
		http.send(HttpRequest.HttpMethod.POST, Urls.NEW_USER_LOGIN, params,
				new RequestCallBack<String>() {

					@Override
					public void onFailure(HttpException arg0, String arg1) {
						handler.sendEmptyMessage(LOGIN_FAIL);
					}

					@Override
					public void onSuccess(ResponseInfo<String> arg0) {
						String result = arg0.result;
						LogUtil.d("wxf", "result:" + result);
						if (result == null) {
							Message msg = handler.obtainMessage();
							msg.what = LOGIN_FAIL;
							handler.sendMessage(msg);
						} else {
							try {
								JSONObject obj = new JSONObject(result);
								String message = obj.getString("message");
								int state = obj.getInt("state");
								if (state == 200) {
									User user = mapper.readValue(
											obj.getString("data"),
											new TypeReference<User>() {
											});
									LogUtil.d("wxf", obj.getString("data"));
									if (user != null) {

										spfUtil.saveObject(user, "user");

									}
									handler.sendEmptyMessage(LOGIN_SUCCESS);

								} else {
									Message msg = handler.obtainMessage();
									msg.obj = message;
									msg.what = LOGIN_FAIL;
									handler.sendMessage(msg);
								}
							} catch (Exception e) {
								LogUtil.e("wxf", e.toString());
								Message msg = handler.obtainMessage();
								msg.what = LOGIN_FAIL;
								handler.sendMessage(msg);
							}
						}
					}

				});
		

	}

}
